const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: [],
    indicatorDots: true,
    autoplay: false,
    interval: 5000,
    duration: 1000,
    number: 0,
    typeindex: -1,
    show: false,
    product: {},
    type: [], //类型名字
    typeprce: [], //类型价格
    comment: {},
    cartype: '', //判断规格是否选择
    id:'',  //产品id
    uid: '',
    level: '',
    carnum: 0 ,//购物车数量
    rich:'',
    sid:'',
    nullshow:false,
    id: '',  //产品id
    poster:'',
    qrshow:false,
  },
  bindsave(e) {
    let that = this
    let image = ''
    if (e.currentTarget.dataset.url){
     image = e.currentTarget.dataset.url
      console.log(image)
    } else if (e.currentTarget.dataset.rich){
      let rich = e.currentTarget.dataset.rich
      let img1 = rich.split('src="')[1];
      let img2 = img1.split('"')[0]
      image = img2.replace(/\"/g, "");
      console.log(1, img1, 2, img2)
      console.log(image)
    }
    
    wx.getImageInfo({
      src: image,
      success: function (res) {
        console.log(res)
        let imageWX = res.path
        wx.saveImageToPhotosAlbum({
          filePath: imageWX,
          success: (res) => {
            wx.showToast({
              title: "已保存到相册",
              icon: 'none',
              duration: 2000,
              mask: true
            })
          },
          fail: function (res) {
            console.log(res)
            //首次保存会询问你是否授权，选是就好了
            if (res.errMsg == "saveImageToPhotosAlbum:fail auth deny") {
              that.setData({ istrue: true })
            }
          }
        })
      }
    })
  },
  // 获取授权
  bindimpower() {
    wx.openSetting({
      success(settingdata) {
        console.error(settingdata)
        if (settingdata.authSetting["scope.writePhotosAlbum"]) {
          console.log("获取权限成功，再次点击图片保存到相册")
        } else {
          console.log("获取权限失败")
        }
      }
    })
  },
  //转发
   onShareAppMessage(res) {
    // if (res.from === 'button') {
    //   // 来自页面内转发按钮
    //   console.log(res.target)
    // }
    console.log('uid',this.data.uid)
     console.log('title',this.data.product.title)
    return {
      title:'宝芝林',
      path: '/pages/login/welcome?scene='+this.data.uid
    }
  },
  // 加
  bindPlus() {
    let number = this.data.number
    number++
    this.setData({
      number: number
    })
  },
  // 减
  bindMinus() {
    let number = this.data.number
    if (number > 1) {
      number--
    }
    this.setData({
      number: number
    })
  },
  // 选择规格
  // chooseType: function(e) {
  //   let typeindex = e.currentTarget.dataset.idx
  //   let item = e.currentTarget.dataset.item
  //   this.setData({
  //     typeindex: typeindex,
  //     cartype: item
  //   })
  // },
  // 显示
  typebox() {
    this.setData({
      show: true,
      number:1
    })
    console.log(this.data.show)
  },
  // 隐藏
  typeboxhidden() {
    this.setData({
      show: false
    })
    console.log(this.data.show)
  },
  // 跳评论
  jumpspeak: function(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/speak/speak?gid=' + id
    })
  },
  //客服
  jumphelp(){
    wx.navigateTo({
      url: '/pages/person/help/help',
    })
  },
  // 加购物车
  addcars() {
    let that = this
    if (that.data.number == 0) {
      that.setData({
        show: true,
        number:1
      })
      wx.showToast({
        title: '请选择具体数量',
        icon: 'none'
      })
    } else {
      wx.request({
        url: app.globalData.api + "addcart",
        data: {
          uid: that.data.uid,
          gid: that.data.product.id,
          num: that.data.number,
          price: that.data.product.price,
          guige: that.data.cartype,
          yunfei: that.data.product.yunfei,
          type:0,
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        success: function(res) {
          console.log(res)
          if (res.data.code == 0) {
            wx.showToast({
                title: '添加成功',
                icon: 'success',
                duration: 2000
              }),
              that.setData({
                show: false,
                cartype: '',
                typeindex: -1,
                number: 1,
                carnum: res.data.count
              })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          }
        },
      })
    }
  },
  //购买
  buynow() {
    let that = this
    let good = []
    good = [{
      gid: that.data.product.id,
      num: that.data.number,
      guige: that.data.cartype,
      price: that.data.product.price,
      type:0
    }]
    // good = JSON.stringify(good)
    console.log('good',good)
    let carts = []
    carts.push({
      gid: that.data.product.id,
      num: that.data.number,
      price: that.data.product.price,
      yunfei: that.data.product.yunfei,
      
    })
    let detail = []
    detail.push(that.data.product)
    console.log('商品', detail)
    delete detail[0].content;
    let final = Object.assign(detail[0], good[0]);//最终对象
    let finalarray = []
    finalarray.push(final)
    console.log('最终数组',finalarray)
    let car = (encodeURIComponent(JSON.stringify(finalarray))) //商品数据
    
    if (that.data.number == 0) {
      that.setData({
        show: true,
        number:1
      })
      wx.showToast({
        title: '请选择具体数量',
        icon: 'none'
      })
    } else {
      carts = JSON.stringify(carts)
      // 获取的计算总价
      wx.request({
        url: app.globalData.api + "getcarttotal",
        data: {
          uid: that.data.uid,
          // level: that.data.level,
          carts: carts,
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        success: function(res) {
          console.log('总价', res)
          wx.navigateTo({
            url: '/pages/buynow/buynow?uid=' + that.data.uid + '&sid=' + that.data.sid + '&goods=' + car + '&total=' + res.data.total + '&price=' + res.data.price + '&yunfei=' + that.data.product.yunfei +'&bean='+res.data.bean+ '&num=' + that.data.number
          })
        },
      })
    }
  },
  //跳购物车
  jumpcar() {
    wx.switchTab({
      url: '/pages/car/carIndex',
    })
  },
  // 获取海报
  getqr(){
    wx.request({
      url: app.globalData.api + "getposter",
      data: {
        uid: this.data.uid,
        level: this.data.level,
        id:this.data.id,
        type:1
      },
      success:(res)=> {
        console.log('海报',res)
        this.setData({
          poster:res.data.img,
          qrshow:true
        })
     
      },
    })
  },
  close(){
    this.setData({
      qrshow: false
    })
  },
  // 保存海报
  saveposter() {
    wx.getImageInfo({
      src: this.data.poster,
      success:(res)=> {
        console.log(res)
        let imageWX = res.path
        wx.saveImageToPhotosAlbum({
          filePath: imageWX,
          success: (res) => {
            wx.showToast({
              title: "已保存到相册",
              icon: 'none',
              duration: 2000,
              mask: true
            })
            this.setData({
              qrshow: false
            })
          },
          fail: (res)=> {
            console.log(res)
            //首次保存会询问你是否授权，选是就好了
            if (res.errMsg == "saveImageToPhotosAlbum:fail auth deny") {
              that.setData({ istrue: true })
            }
          }
        })
      }
    })
  },
  // 获取授权
  bindimpower() {
    wx.openSetting({
      success(settingdata) {
        console.error(settingdata)
        if (settingdata.authSetting["scope.writePhotosAlbum"]) {
          console.log("获取权限成功，再次点击图片保存到相册")
        } else {
          console.log("获取权限失败")
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this
    wx.getStorage({
      key: 'userinfo',
      success: function(res) {
        console.log(res.data.id)
        that.setData({
          uid: res.data.id,
          level: res.data.level,
          sid: res.data.sid,
          id: options.id
        })
        wx.request({
          url: app.globalData.api + "getgoodsdetail",
          data: {
            id: options.id,
            uid:res.data.id,
            // level: res.data.level
          },
          success: function(res) {
            console.log('商品',res)
            if(res.data.code!=1){
                that.setData({
                  nullshow:true
                })
            }else{
              let lunbo = res.data.list.img
              let imgbox = new Array()
              imgbox = lunbo.split(',')
              let rich = res.data.list.content.replace(/<img /g, '<img class="rich_img"')
              that.setData({
                product: res.data.list,
                carnum: res.data.count,
                // type: typelist,
                // typeprce: typeprce,
                comment: res.data.comment,
                imgUrls: imgbox,
                rich: rich
              })
            }
          },
        })
      },
    })


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    wx.hideShareMenu()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

})